/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef SHARED_UTIL_APPLICATION_H_
#define SHARED_UTIL_APPLICATION_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <ctime>
#include <string>
#include "Shared/Global_Macros.h"
#include "Shared/Util/OptionSet.h"
#include "Shared/Log/Log.h"
#include "Shared/Util/IniFile.h"

namespace Shared {
namespace Util {

    class Application
    {
    public:
        enum ExitCode
        {
            EXIT_OK = 0,
            EXIT_USAGE = 64,
            EXIT_CONFIG = 65,
            EXIT_MEMORY = 66,
            EXIT_SUBSYSTEM = 67,
            EXIT_LOG = 68,
            EXIT_SOFTWARE = 70,
        };

        Application(const char *appName = "Application", const char *defaultConf = "");
        virtual ~Application(void);

        int run(int argc, char* argv[]);
        void hookSignal(int signal, bool ignore = false);
        void unhookSignal(int signal);

        static Application *instance(void) { return _instance; }
        time_t uptime(void) const { return _upTime; }
        Util::IniFile &config(void) { return _config; }

    protected:
        virtual void onDefineOptions(Util::OptionSet& options);
        virtual int onOption(const std::string& name, const std::string& arg);
        virtual void onSignal(int signal);
        virtual int onInitialize(void) = 0;
        virtual void onUninitialize(void) = 0;
        virtual int main(std::vector<std::string>& unknownArgs) = 0;

    private:
        int initialize(int argc, char* argv[]);
        void uninitialize(void);
        void showUsage(void);
        static void signalHandler(int signal);

        const char *_name;
        std::vector<std::string> _arguemnts;
        Util::OptionSet _options;
        time_t _upTime;
        Util::IniFile _config;
        std::string _configPath;
        Log _log;
        static Application *_instance;
        DISALLOW_COPY_AND_ASSIGN(Application);
    };

}}

#define sharedApp       (*(Shared::Util::Application::instance()))
#define sharedAppConfig sharedApp.config()

#endif // SHARED_UTIL_APPLICATION_H_
